package com.mitake.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.json.JSONArray;
import org.json.JSONObject;

import com.mitake.parse.MonthK;
import com.mitake.parse.DayK.DayKItem;
import com.mitake.parse.MonthK.MonthKItem;
import com.mitake.task.monthK.MonthKCompareProcess;
import com.mitake.task.monthK.MonthKCompareTask;
import com.mitake.utils.ExcelUtil;
import com.mitake.utils.Util;

/**
 * 月K监听
 * @author Administrator
 *
 */
@SuppressWarnings("serial")
public class MonthKActionServlet extends HttpServlet {
	
	public  FileOutputStream fos;
	
	public MonthKActionServlet() {
		super();
	}
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType(Util.CONTENT_TYPE);
		request.setCharacterEncoding(response.getCharacterEncoding());
		String event = request.getParameter("event");
		//String src = request.getParameter("src");
		String data = "";
		MonthKCompareTask monthKCompareTask =MonthKCompareTask.getInstance();
		
		if (event.equals("f")){
			request.getRequestDispatcher("/monthm-compare.jsp").forward(request, response);
		}else if(event.equals("s")){
			ServletContext context = getServletContext();
			String rootPath = context.getRealPath("");
			/**
			 * 取得询问报告间隔时间
			 */
			monthKCompareTask.setRunInterval(Util.getRunInterval(rootPath));
			/**
			 * 取得商品
			 */
			monthKCompareTask.setStockList(Util.getStock(rootPath));
			/**
			 * 取得各机房IP
			 */
			monthKCompareTask.start(Util.getHost(rootPath));
			data = "{\"code\":\"00000\",\"message\":\"程序启动中\"}";
	        PrintWriter out = response.getWriter();
	        out.println(data);	
		} else if(event.equals("e")) {
			monthKCompareTask.stop();
			
			data = "{\"code\":\"00000\",\"message\":\"程序停止中\"}";
	        PrintWriter out = response.getWriter();
	        out.println(data);	
		} else if(event.equals("g")){
			String[][] status = monthKCompareTask.getAllSocketStatus();
			StringBuilder t = new StringBuilder();
			if(status != null) {
				t.append("[");
				
				for(int i = 0 ; i < status.length ; i++) {
					t.append("{");
					t.append("\"ip\":\"").append(status[i][0]).append("\",");
					t.append("\"status\":\"").append(status[i][1]).append("\"");
					t.append("},");
				}
				
				t.setLength(t.length() - 1);
				t.append("]");
			}
			String[] count = monthKCompareTask.getTelegramCount();
			StringBuilder tmp = new StringBuilder();
			tmp.append("{");
			tmp.append("\"code\":\"00000\",");
			tmp.append("\"message\":\"ok\",");
			tmp.append("\"running\":");
			tmp.append((monthKCompareTask.isRunning() ? "\"true\"" : "\"false\"")).append(",");
			tmp.append("\"w\":\"");
			tmp.append(count[0]).append("\",");
			tmp.append("\"r\":\"");
			tmp.append(count[1]).append("\",");
			tmp.append("\"host\":");
			tmp.append(t.length() > 0 ? t : "\"\"").append(",");
			MonthK[] monthKs = MonthKCompareProcess.data;
			if (monthKs != null) {
				tmp.append("\"push\":[");
				MonthK flagMonthK = monthKs[0];

				for (Map.Entry<String, MonthKItem> entry : flagMonthK.monthKMap.entrySet()) {
					MonthKItem flagMonthKItem = entry.getValue();
					String key = entry.getKey();
					tmp.append("{\"").append(key).append("\":"); // [{date1:[{},{}]},{date1:[{},{}]}]
					tmp.append("[");

					for (int i = 1; i < monthKs.length; i++) {
						if (i != 1) {
							tmp.append(",");
						}
						MonthK monthK = monthKs[i];
						MonthKItem monthKItem = monthK.monthKMap.get(key);
						tmp.append("{");
						tmp.append("\"host\":").append("\"").append(monthK.host).append("\",");
						tmp.append("\"ip\":").append("\"").append(monthK.ip).append("\",");
						tmp.append("\"date\":").append("\"").append(monthKItem.date).append("\",");
						tmp.append("\"time\":").append("\"").append(monthKItem.time).append("\",");
						tmp.append("\"firstPrice\":").append("\"").append(monthKItem.firstPrice).append("\",");
						tmp.append("\"highPrice\":").append("\"").append(monthKItem.highPrice).append("\",");
						tmp.append("\"lowPrice\":").append("\"").append(monthKItem.lowPrice).append("\",");
						tmp.append("\"lastPrice\":").append("\"").append(monthKItem.lastPrice).append("\",");
						tmp.append("\"volume\":").append("\"").append(monthKItem.volume).append("\",");
						tmp.append("\"reference\":").append("\"").append(monthKItem.reference).append("\",");
						tmp.append("\"firstPrice_flag\":").append("\"").append(flagMonthKItem.firstPrice).append("\",");
						tmp.append("\"highPrice_flag\":").append("\"").append(flagMonthKItem.highPrice).append("\",");
						tmp.append("\"lowPrice_flag\":").append("\"").append(flagMonthKItem.lowPrice).append("\",");
						tmp.append("\"lastPrice_flag\":").append("\"").append(flagMonthKItem.lastPrice).append("\",");
						tmp.append("\"volume_flag\":").append("\"").append(flagMonthKItem.volume).append("\",");
						tmp.append("\"reference_flag\":").append("\"").append(flagMonthKItem.reference).append("\"");
						tmp.append("}");
					}

					tmp.append("]");
					tmp.append("},");
					// }
				}

				// 去掉最后一个,
				String strtmp = tmp.toString();
				tmp.setLength(0);
				tmp.append(strtmp.substring(0, strtmp.length() - 1));

				tmp.append("],");

				tmp.append("\"index\":").append("\"").append(-1).append("\"");
			} else {
				tmp.append("\"push\":\"\"");
			}
			tmp.append("}");
			data = tmp.toString();
	        PrintWriter out = response.getWriter();
	        out.println(data);	
		}else if(event.equals("download")){
			response.setCharacterEncoding("utf-8");
			MonthK[] monthKs = MonthKCompareProcess.data;
			MonthK flagMonthK = monthKs[0];
			StringBuilder tmp = new StringBuilder();
			tmp.append("[");
			for(Map.Entry<String, MonthKItem> entry : flagMonthK.monthKMap.entrySet()){
					String key = entry.getKey();
					MonthKItem flagMonthKItem = entry.getValue();  
					tmp.append("{\"").append(key).append("\":");  //[{date1:[{},{}]},{date1:[{},{}]}]
					tmp.append("[");
					for(int i = 1; i < monthKs.length; i++){
						if(i != 1 ){
							tmp.append(",");
						}
						MonthK monthK = monthKs[i];
						MonthKItem monthKItem = monthK.monthKMap.get(key);
						tmp.append("{");
						tmp.append("\"host\":").append("\"").append(monthK.host).append("\",");
						tmp.append("\"ip\":").append("\"").append(monthK.ip).append("\",");
						tmp.append("\"date\":").append("\"").append(monthKItem.date).append("\",");
						tmp.append("\"time\":").append("\"").append(monthKItem.time).append("\",");
						tmp.append("\"firstPrice\":").append("\"").append(monthKItem.firstPrice).append("\",");
						tmp.append("\"highPrice\":").append("\"").append(monthKItem.highPrice).append("\",");
						tmp.append("\"lowPrice\":").append("\"").append(monthKItem.lowPrice).append("\",");
						tmp.append("\"lastPrice\":").append("\"").append(monthKItem.lastPrice).append("\",");
						tmp.append("\"volume\":").append("\"").append(monthKItem.volume).append("\",");
						tmp.append("\"reference\":").append("\"").append(monthKItem.reference).append("\",");
						tmp.append("\"firstPrice_flag\":").append("\"").append(flagMonthKItem.firstPrice.equals("@")?1:0).append("\",");
						tmp.append("\"highPrice_flag\":").append("\"").append(flagMonthKItem.highPrice.equals("@")?1:0).append("\",");
						tmp.append("\"lowPrice_flag\":").append("\"").append(flagMonthKItem.lowPrice.equals("@")?1:0).append("\",");
						tmp.append("\"lastPrice_flag\":").append("\"").append(flagMonthKItem.lastPrice.equals("@")?1:0).append("\",");
						tmp.append("\"volume_flag\":").append("\"").append(flagMonthKItem.volume.equals("@")?1:0).append("\",");
						tmp.append("\"reference_flag\":").append("\"").append(flagMonthKItem.reference.equals("@")?1:0).append("\"");
						tmp.append("}"); 
					}
					tmp.append("]");
					tmp.append("},");
			}
			//去掉最后一个,
			String strtmp = tmp.toString();
			tmp.setLength(0);
			tmp.append(strtmp.substring(0, strtmp.length()-1));
			tmp.append("]");
			 
			JSONArray jArray = new JSONArray(tmp.toString());
			String path = ExcelUtil.processExcel(jArray,request.getServletContext());
			response.setHeader("content-disposition", "attachment;filename=monthK"+System.currentTimeMillis()+".xls");
			InputStream in = new FileInputStream(path);
			int len = 0;
			byte[] buffer = new byte[1024];
	         //6.通过response对象获取OutputStream流
	         OutputStream out = response.getOutputStream();
	         //7.将FileInputStream流写入到buffer缓冲区
		      while ((len = in.read(buffer)) > 0) {
		      //8.使用OutputStream将缓冲区的数据输出到客户端浏览器
		          out.write(buffer,0,len);
		      }
		      in.close();
		}

	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}

}
